import 'dart:io';

import 'package:path_provider/path_provider.dart';

/// @Author 杨璐铭
/// @Date 2023/6/23 8:51 PM
/// @describe 文件管理
class FileUtils {
  static const int sizeOneKB = 1024;
  static const int sizeOneMB = 1048576;
  static const int sizeOneGB = 1073741824;

  ///根目录
  static Future<Directory> _getRoot() => getApplicationSupportDirectory();

  ///获取一个file
  static Future<File> getFile(String name) async {
    String root = (await _getRoot()).path;
    return File('$root/$name');
  }

  ///获取一个file
  static Future<String> getUploadFile() async {
    String root = (await _getRoot()).path;
    return File('$root/upload_thumb.jpg').path;
  }

  ///获取缓存大小
  static Future<String> getCacheSize() async {
    return getSizeStr(await getSize(await _getRoot()));
  }

  ///清空缓存
  static Future clearCache() async {
    return deleteFile(await _getRoot());
  }

  ///获取这个文件的大小
  static Future<double> getSize(FileSystemEntity file) async {
    if (file is File) {
      return (await file.length()).toDouble();
    }
    double size = 0;
    List<FileSystemEntity> temp = await (file as Directory).list().toList();
    for (int i = 0; i < temp.length; i++) {
      double tempSize = await getSize(temp[i]);
      size += tempSize;
    }
    return size;
  }

  ///获取大小字符串
  static String getSizeStr(double size) {
    String result = "0B";
    if (size < sizeOneKB) {
      result = "${size}B";
    } else if (size < sizeOneMB) {
      result = "${(size / sizeOneKB).toStringAsFixed(2)}KB";
    } else if (size < sizeOneGB) {
      result = "${(size / sizeOneMB).toStringAsFixed(2)}MB";
    } else {
      result = "${(size / sizeOneGB).toStringAsFixed(2)}GB";
    }
    return result;
  }

  ///删除这个文件
  static Future<dynamic> deleteFile(FileSystemEntity file) async {
    if (file is File) {
      if (file.existsSync()) return await file.delete();
      return null;
    }
    List<FileSystemEntity> temp = await (file as Directory).list().toList();
    for (int i = 0; i < temp.length; i++) {
      await deleteFile(temp[i]);
    }
    return null;
  }
}
